using System;

namespace EntityKit.Runtime
{
    /// <summary>
    /// 统一状态节点基类
    /// </summary>
    public abstract class StateNode : IStateNode
    {
        protected StateMachine Machine { get; private set; }
        protected object OwnerEntity => Machine.OwnerEntity;
        private EventGroup mEventGroup = null;
        public virtual void OnCreate(StateMachine machine)
        {
            Machine = machine ?? throw new ArgumentNullException(nameof(machine));
        }

        public virtual void OnEnter()
        {
            mEventGroup = new EventGroup();
        }

        public virtual void OnExit()
        {
            mEventGroup.RemoveAllListener();
        }



        public virtual void OnUpdate()
        {
        }

        public virtual void OnReason()
        {
        }
        
        public virtual void OnRelease(bool isCurNode)
        {
            
        }
        
        /// <summary>
        /// 添加事件监听器
        /// </summary>
        protected void AddEventListener<TEvent>(System.Action<IEventMessage> listener) where TEvent : IEventMessage
        {
            mEventGroup.AddListener<TEvent>(listener);
        }

        /// <summary>
        /// 发送事件消息
        /// </summary>
        protected void SendEventMessage(IEventMessage message)
        {
            EventKit.SendMessage(message);
        }

        /// <summary>
        /// 延迟发送事件消息
        /// </summary>
        protected void PostEventMessage(IEventMessage message)
        {
            EventKit.PostMessage(message);
        }
    }

    /// <summary>
    /// 强类型状态节点基类
    /// </summary>
    public abstract class StateNode<T> : StateNode where T : class
    {
        protected new T OwnerEntity => (T)base.OwnerEntity;
    }
}